package com.codeduck.poi.controller.excel;

import com.codeduck.poi.util.AttachmentExportUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author: <a href="mailto:codeduck@163.com">Codeduck</a>
 * @date: 2023/2/4
 */
@RestController
public class DateCellController {

    @GetMapping("write/date/into/cells")
    public void writeDate(HttpServletResponse response) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("sheet1");
        Row row = sheet.createRow(0);

        // 格式化方式一
        CreationHelper helper = workbook.getCreationHelper();
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setDataFormat(helper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));

        Cell cell = row.createCell(0);
        cell.setCellValue(new Date());
        cell.setCellStyle(cellStyle);

        cell = row.createCell(1);
        cell.setCellValue(LocalDateTime.now());
        cell.setCellStyle(cellStyle);

        // 格式化方式二
        CellStyle cellStyle1 = workbook.createCellStyle();
        cellStyle1.setDataFormat(helper.createDataFormat().getFormat("yyyy-MM-dd"));

        cell = row.createCell(2);
        cell.setCellValue(new Date());
        cell.setCellStyle(cellStyle1);

        cell = row.createCell(3);
        cell.setCellValue(LocalDate.now());
        cell.setCellStyle(cellStyle1);

        AttachmentExportUtil.export(workbook, "writeDateIntoCellsTest", response);
    }

    /**
     * 从cell中读取时间类型：
     *  case NUMERIC:
     *      // NUMERIC类型的数据：整数，小数，日期
     *      if (HSSFDateUtil.isCellDateFormatted(cell)) {
     *          Date date = DateUtil.getJavaDate(cell.getNumericCellValue());
     *          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     *          sb.append(sdf.format(date) + "(DATE)");
     *      } else {
     *          sb.append(cell.getNumericCellValue() + "(NUMERIC)");
     *      }
     *      break;   // NUMERIC类型的数据：整数，小数，日期
     */

}
